<template>
  <div class="image-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ name: 'home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>素材管理</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 面包屑 -->
      </div>

      <!-- fit:填充模式 
        change	绑定值变化时触发的事件
      -->
      <div class="action-head">
        <el-radio-group v-model="collect" size="mini" @change="loadImages(1)">
          <el-radio-button :label="false">全部</el-radio-button>
          <el-radio-button :label="true">收藏</el-radio-button>
        </el-radio-group>
        <el-button
          size="mini"
          style="float: right; padding: 3px 0"
          type="success"
          @click="dialogUploadVisible = true"
          >上传素材</el-button
        >
      </div>
      <!-- 素材列表 -->
      <el-row :gutter="10">
        <el-col
          :xs="12"
          :sm="6"
          :md="6"
          :lg="4"
          v-for="(img, index) in images"
          :key="index"
          class="image-item"
        >
          <el-image style="height: 150px" :src="img.url" fit="cover"></el-image>
          <div class="image-action">
            <el-button
              type="warning"
              :icon="img.is_collected ? 'el-icon-star-on' : 'el-icon-star-off'"
              circle
              size="mini"
              @click="onCollect(img)"
              :loading="img.loading"
            ></el-button>
            <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete-solid"
            circle
            @click="onDelect(img)"
            :loading="img.loading"
            ></el-button>
            <!-- 样式绑定 -->
            <!-- <li
            :class="{
              '':  img.is_collected,
              'el-icon-star-off': !img.is_collected,
            }"
           
            ></li> -->
            <!-- <li class="el-icon-delete-solid"></li> -->
          </div>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <!-- 分页数据改变以后，页码不会变化，他需要单独处理高亮的页码  -->
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :current-page.sync="page"
        @current-change="loadImages"
        :total="totalCount"
      >
      </el-pagination>
      <!-- 分页 -->
    </el-card>

    <!-- :visible.sync 对弹出层的显示和隐藏 -->
    <el-dialog
      title="上传素材"
      :visible.sync="dialogUploadVisible"
      :append-to-body="true"
    >
      <!-- 
      upload 组件本身就支持请求提交上传操作，说白了你使用它不用自己去发请求，，它会自己发。选了文件之后自己就上传提交
      请求方法：默认就是POST
      请求路径：action，，必须写完整路径（不用axios发送请求，）

      :on-success 上传成功的钩子函数
     -->
      <el-upload
        class="upload-demo"
        drag
        action="http://api-toutiao-web.itheima.net/mp/v1_0/user/images"
        :headers="uploadHeaders"
        name="image"
        :show-file-list="false"
        :on-success="onUploadSuccess"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getImages,
  collectImage,
  DelectImage 
} from "@/api/image";

export default {
  name: "ImageIndex",
  data() {
    const user = JSON.parse(window.localStorage.getItem("user"));
    return {
      images: [], //图片素材列表
      collect: false, //默认查询全部素材列表
      dialogUploadVisible: false, //默认隐藏弹出层
      uploadHeaders: {
        Authorization: `Bearer ${user.token}`,
      },
      totalCount: 0, //总条目个数
      page: 1, //当前页数 默认第一页
      pageSize: 12, //每页显示条目
      
    };
  },
  created() {
    this.loadImages(1);
  },
  methods: {
    loadImages(page) {
      // 重置高亮页码 防止数据和页码不对应
      this.page = page;
      getImages({
        collect: this.collect,
        page,
        per_page: this.pageSize,
      }).then((res) => {
        const results = res.data.data.results;
        results.forEach(img => {
          // img对象本来没有loading 数据
          // 我们这里收到的往里面添加该数据是用来控制每个收藏按钮的 loading 状态
          img.loading = false
        })
        this.images = results
        this.totalCount = res.data.data.total_count;
      });
    },

    // onCollectChange() {
    //   // console.log(value);
    //   this.loadImages(1);
    // },

    // 素材上传成功 调用此函数
    onUploadSuccess() {
      // 关闭对话框
      this.dialogUploadVisible = false;
      // 更新素材列表 回到第一页
      this.loadImages(this.page);

      this.$message({
        type: "success",
        message: "上传成功",
      });
    },

// 添加，取消收藏
    onCollect(img) {
      // 展示loading
      img.loading = true
      collectImage(img.id, !img.is_collected).then((res) => {
        // 更新视图状态
        img.is_collected = !img.is_collected;
        // 关闭loading
        img.loading = false
      });
    },
    
// 删除图片
    onDelect(img) {
      img.loading = true
      DelectImage(img.id).then(res => {
        // 重新加载数据列表
        this.loadImages(this.page)
        img.loading = false
      })
    }
  },
};
</script>

<style scoped lang="less">
.action-head {
  padding-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.image-item {
  position: relative;
}

.image-action {
  font-size: 25px;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  color: #fff;
  height: 40px;
  background-color: rgba(204, 204, 204, 0.5);
  position: absolute;
  bottom: 4px;
  left: 5px;
  right: 5px;
}
</style>